package com.emapp.lccode.activity

import android.os.Bundle
import android.view.View
import com.emapp.lccode.BuildConfig
import com.emapp.lccode.R
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.databinding.ActivityMobileCodeBinding
import com.emapp.lccode.mode.LoginKtViewModel
import com.emapp.lccode.utils.BaseUtil
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.countDownCoroutines
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.toStartActivity
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.Toaster
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 登录
 */
class LoginKtActivity : BaseActivity1<LoginKtViewModel, ActivityMobileCodeBinding>() {
//15106932627  13645418008
    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            titleBar(mViewBind.lvTitle.ivBar)
            statusBarDarkFont(true)
            fullScreen(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        mViewBind.lvTitle.tvTitle.text = "登录"
        mViewBind.lvTitle.tvRight.visibility = View.GONE
        mViewBind.lvTitle.tvTitle.setTextColor(resources.getColor(R.color.white))
        mViewBind.lvTitle.ivLeft.setImageResource(R.drawable.title_left_white)
        EventBus.getDefault().register(this)
        mViewBind.evName.setText(MmkvUtil.getString("username", ""))
        val v = BaseUtil.getAppVersionName(this)
        mViewBind.tvVersion.text =  "(${BaseConfig.versions[BaseConfig.v].name}) ${BuildConfig.BUILD_TYPE}-$v"
        mViewModel.getImageCode()
        mViewBind.ivAvatar.setOnClickListener {
            val currentTime = System.currentTimeMillis()
            // 防止快速连击，确保两次点击之间至少有MIN_CLICK_INTERVAL的间隔
            if (currentTime - lastClickTime >1) {
                clickCount++
                log_e("clickCount::"+clickCount)
                lastClickTime = currentTime
                if (clickCount == CLICK_COUNTDOWN) {
                    // 达到5次点击，执行相应操作
                    // onButtonClick5Times()
                    toStartActivity(AdminListActivity::class.java)
                    clickCount = 0 // 重置点击计数器
                }
            }
        }
    }
    private var clickCount = 0 // 点击计数器
    private val CLICK_COUNTDOWN = 5 // 需要连续点击的次数
    private var lastClickTime: Long = 0 // 记录上一次点击的时间，用于防抖动处理

    override fun createObserver() {
        mViewModel.run {
            bitmap.observe(this@LoginKtActivity) { result ->
                if (result == null) {
                    Toaster.show("获取图形验证码失败")
                } else {
                    mViewBind.ivCode.setImageBitmap(result)
                }
            }
            code.observe(this@LoginKtActivity) { result ->
                parseState(result, {
                    countDownCoroutines(60, { re ->
                        mViewBind.btCode.isClickable = false
                        mViewBind.btCode.text = re.toString() + "s"
                    }, {
                        mViewBind.btCode.isClickable = true
                        mViewBind.btCode.text = "重新获取"
                    })
                }, {
                    Toaster.show(it.errorMsg)
                })
            }

            user.observe(this@LoginKtActivity) { result ->
                if (result!=null){
                    BaseApplication.instance.setUser(result)
                    log_e("ddddd   "+result.admin_id)
                    MmkvUtil.putBoolean("isAutoLogin", true)
                    MmkvUtil.putInt("city_version", BaseConfig.v)
                    toStartActivity(MainKtActivity::class.java)
                    finish()
                }
//                parseState(result, {
//                    //MmkvUtil.putString("username", it.name);

//                }, {
//                    Toaster.show(it.errorMsg)
//                })
            }
        }
    }

    override fun onResume() {
        super.onResume()
        clickCount = 0
    }
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.lvTitle.ivLeft,
            mViewBind.lvTitle.tvRight,
            mViewBind.ivCode,
            mViewBind.btCode,
            mViewBind.btOk,
        ) {
            when (it.id) {
                R.id.iv_left -> {
                    finish()
                }

                R.id.iv_code -> {
                    mViewModel.getImageCode()
                }

                R.id.bt_code -> {
                    var mobile = mViewBind.evName.text.toString()
                    if (mobile.isEmpty()) {
                        Toaster.show("请输入账号")
                        return@setOnclickNoRepeat
                    }
                    if (mobile.length != 11) {
                        Toaster.show("请输入11位手机号")
                        return@setOnclickNoRepeat
                    }
                    var imageCode = mViewBind.evImgCode.text.toString()
                    if (imageCode.isEmpty()) {
                        Toaster.show("请输入图形验证码")
                        return@setOnclickNoRepeat
                    }
                    mViewModel.codeGet(mobile, imageCode)
                }

                R.id.bt_ok -> {
                    val mobile = mViewBind.evName.text.toString()
                    if (mobile.isEmpty()) {
                        Toaster.show("请输入账号")
                        return@setOnclickNoRepeat
                    }
                    if (mobile.length != 11) {
                        Toaster.show("请输入11位手机号")
                        return@setOnclickNoRepeat
                    }
                    val imageCode = mViewBind.evImgCode.text.toString()
                    if (imageCode.isEmpty()) {
                        Toaster.show("请输入图形验证码")
                        return@setOnclickNoRepeat
                    }
                    val code = mViewBind.evPassword.text.toString()
                    if (code.isEmpty()) {
                        Toaster.show("请输入短信验证码")
                        return@setOnclickNoRepeat
                    }
                    mViewModel.login(mobile, code, imageCode)
                }

            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.FINISH_APP -> {
                finish()
            }

            else -> {}
        }
    }

}
